<?php

namespace plugin\voice\app\controller;

use support\Request;
use support\Response;
use Webman\Medoo\Medoo as db;
use Webman\Captcha\CaptchaBuilder;
use plugin\user\api\Captcha;
use support\Redis;

class LoginController{
    
    protected $noNeedLogin = ['index','code','test','reg'];
    
    // public function test(Request $request){
    //     $inputs     = $request->rawBody();
    //     $inputArray = explode(PHP_EOL,$inputs);
    //     foreach ($inputArray as $input) {
    //         $key = explode('----',$input)[2];
    //         $check = db::get('ai_apikeys','*',['apikey' => $key]);
    //         if(!$check){
    //             $data = [];
    //             $data['apikey'] = $key;
    //             $data['dalle']  = 0;
    //             db::insert('ai_apikeys',$data);
    //         }
    //     }
    //     return 'ok';
    // }
    public function setCode($key, $code){
        $setting = db::get('voice_settings','*');
        if($setting['redis_enable']){
            Redis::set($key,$code);
        }else{
            $checkVerify = db::get('voice_verify','*',['status' => 1, 'uuid' => $key]);
            if($checkVerify){
                db::update('voice_verify',['status' => 3],['id' => $checkVerify['id']]);
            }
            if($code){
                db::insert('voice_verify',['code' => $code, 'uuid' => $key]);
            }
        }
    }
    
    public function getCode($key){
        $setting = db::get('voice_settings','*');
        if($setting['redis_enable']){
            return Redis::get($key);
        }else{
            $checkVerify = db::get('voice_verify','*',['status' => 1, 'uuid' => $key]);
            if($checkVerify){
                $timeDiff = time() - strtotime($checkVerify['insert_time']);
                if($timeDiff < 300){
                    return $checkVerify['code'];
                }
            }
            return '';
        }
    }
    
    public function verifyCode($code, $verifyCode, $key){
        $setting = db::get('voice_settings','*');
        if($code == $verifyCode){
            self::setCode($key,null);
            if(!$setting['redis_enable']){
                db::update('voice_verify',['status' => 2],['uuid' => $key]);
            }
            return true;
        }
        return '';
    }
    
    public function index(Request $request){
        $username      = $request->post('username');
        $password      = $request->post('password');
        $imageCode     = $request->post('image_code');
        $phoneCode     = $request->post('phone_code');
        $key           = 'verification_code_'.$request->post('uuid');
        $verifyCode    = self::getCode($key);
        if(!$verifyCode){
            return json([
                'code' => 201,
                'msg'  => '验证码不存在'
            ]);
        }
        $verifyResult  = self::verifyCode($imageCode,$verifyCode,$key);
        if(!$verifyResult){
            return json([
                'code' => 201,
                'msg'  => '验证码错误'
            ]);
        }
        $userInfo                     = db::get('voice_users','*',['username' => $username, 'password' => $password]);
        if($userInfo){
            $accessToken              = 'knl'.date('YmdHis').mt_rand(1000000,9999999);
            $userInfo['access_token'] = $accessToken;
            db::update('voice_users', [
                'access_token'        => $accessToken,
                'last_login_time'     => date('Y-m-d H:i:s', time()), 
                'last_login_ip'       => $request->getRealIp() 
            ], ['id' => $userInfo['id']]);
            return json([
                'code' => 201,
                'msg'  => 'ok',
                'data' => $accessToken
            ]);
        }else{
            return json([
                'code' => 201,
                'msg'  => '用户名或密码错误'
            ]);
        }
    }
    
    public function reg(Request $request){
        $username   = $request->post('username');
        $password   = $request->post('password');
        $imageCode  = $request->post('image_code');
        $mail       = $request->post('mail');
        if (!preg_match("/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", $mail)) {
            return json([
                'code' => 201,
                'msg'  => '请输入正确的邮箱'
            ]);
        }
        if(strlen($username) < 6){
            return json([
                'code' => 201,
                'msg'  => '用户名不能少于6位'
            ]);
        }
        if(strlen($password) < 6){
            return json([
                'code' => 201,
                'msg'  => '密码不能少于6位'
            ]);
        }
        $key           = 'verification_code_'.$request->post('uuid');
        $verifyCode    = self::getCode($key);
        if(!$verifyCode){
            return json([
                'code' => 201,
                'msg'  => '验证码不存在'
            ]);
        }
        $verifyResult  = self::verifyCode($imageCode,$verifyCode,$key);
        if(!$verifyResult){
            return json([
                'code' => 201,
                'msg'  => '验证码错误'
            ]);
        }
        $checkUserInfo = db::get('voice_users', 'id',['username' => $username]);
        if($checkUserInfo){
            return json([
                'code' => 201,
                'msg'  => '用户名已存在'
            ]); 
        }
        $checkUserInfo = db::get('voice_users', 'id',['mail' => $mail]);
        if($checkUserInfo){
            return json([
                'code' => 201,
                'msg'  => '邮箱已存在'
            ]);               
        }
        $giftList                      = [];
        $models                        = db::select('voice_models','*',['status' => 1]);
        foreach ($models as $model) {
            $giftList[$model['field']] = $model['reg'];
        }
        $userData                      = [];
        $userData['mail']              = $mail;
        $userData['username']          = $username;
        $userData['password']          = $password;
        $userData['field1']            = $giftList['field1'];
        $userData['field2']            = $giftList['field2'];
        $userData['field3']            = $giftList['field3'];
        $userData['field4']            = $giftList['field4'];
        $userData['field5']            = $giftList['field5'];
        $userData['field6']            = $giftList['field6'];
        $userData['expired_time']      = date('Y-m-d H:i:s',time());
        db::insert('voice_users',$userData);
        return json([
            'code' => 201,
            'msg'  => '注册成功',
            'data' => 'success'
        ]);
    }
    
    public function code(Request $request){
        $builder         = new CaptchaBuilder;
        $captchaData     = Captcha::create();
        $builder->setPhrase($captchaData['code']);
        $builder->build();
        $captchaType     = 'image';
        $uuid            = $request->input('uuid','abcdefghijklmnopqrstuvwxyz');
        $key             = 'verification_code_'.$uuid;
        self::setCode($key,$captchaData['code']);
        $img_content = $builder->get();
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }
    
}
